package cn.sccl.dirms.sms;

import cn.sccl.common.database.DataBase;
import cn.sccl.common.database.DataRow;
import cn.sccl.common.database.DataSet;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.collections.map.ListOrderedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 查找需要发送短信的告警信息 并进行添加到队列中
 * Created by xf-cl on 2017/11/22.10:57
 */
@Service
public class AlertsTask {

    private static Logger log = LoggerFactory.getLogger(AlertsTask.class);
    @Autowired
    private ProducerService producerService;

    @Resource(name="smsSendQueueDestination")
    private ActiveMQQueue smsSendQueueDestination;

    @Autowired
    private DataBase dataBase;
    private int count=0;

    /**
     * 用来调度的方法
     * 查询告警信息
     */
    public void find(){
        count++;
        List<ListOrderedMap> list = query();
        log.debug("我是activeMQ ：我第"+count+"次进来执行，短信告警数据总共"+(list==null?0:list.size()) + "条");
        for(ListOrderedMap map :list){
            producerService.producerSms(smsSendQueueDestination,map);
        }
    }

    /**
     * 根据状态查询告警信息 严重和灾难的
     * @return
     */
    public List<ListOrderedMap> query( ){
        String sql = "select  a.alertid,\n" +
                "        ac.name, \n" +
                "        a.clock,\n" +
                "        a.message content,\n" +
                "        a.`status`,\n" +
                "        m.sendto,\n" +
                "        m.severity ,\n" +
                "        case t.priority when 0 then '未分类'  \n" +
                "                        when 1 then '信息'   \n" +
                "                        when 2 then '警告'   \n" +
                "                        when 3 then '一般严重'   \n" +
                "                        when 4 then '严重'   \n" +
                "                        when 5 then '灾难' else '' end  `priority`\n" +
                "from alerts a\n" +
                "                LEFT JOIN(select * from `events` where object=0 and source=0) e on a.eventid = e.eventid\n" +
                "                INNER JOIN (select triggerid,priority from `triggers` where priority > 3 ) t on e.objectid = t.triggerid\n" +
                "                INNER JOIN media m on m.userid = a.userid\n" +
                "                INNER JOIN (select * from media_type where type = 2) mt on m.mediatypeid = mt.mediatypeid\n" +
                "                INNER JOIN actions ac on ac.actionid = a.actionid\n" +
                "                where  a.`status` != 1 and ac.name = '短信告警' and m.severity in(8,12,16,32,48,56) order by a.clock desc " ;
        return dataBase.queryList(sql);
    }

}
